package com.rabbitmq.rabbitmqdemo.producer;

import com.rabbitmq.rabbitmqdemo.config.RabbitConfig;
import com.rabbitmq.rabbitmqdemo.model.MyModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Author: zhangQi
 * @Date: 2020-07-19 10:31
 */
@Component
public class MyProducer implements RabbitTemplate.ConfirmCallback {

    /**
     * org.slf4j.Logger  log
     */
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 由于rabbitTemplate的scope属性设置为ConfigurableBeanFactory.SCOPE_PROTOTYPE,所以不能自动注入
     */
    private RabbitTemplate rabbitTemplate;

    /**
     * 构造方法注入rabbitTemplate
     * @param rabbitTemplate
     */
    @Autowired
    public MyProducer(RabbitTemplate rabbitTemplate){
        this.rabbitTemplate = rabbitTemplate;
        //rabbitTemplate如果为单例的话,那回调就是最后设置的内容
        rabbitTemplate.setConfirmCallback(this);
    }

    public void sendMsg(MyModel model){
        //把消息放入ROUTINGKEY_A对应的队列当中,对应对列为队列A
        rabbitTemplate.convertAndSend(RabbitConfig.EXCHANGE_A,RabbitConfig.ROUTINGKEY_A,model);
    }

    /**
     * 回调
     */
    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        logger.info("回调id:"+correlationData);
        if(ack){
            logger.info("消息成功消费");
        }else{
            logger.info("消息消费失败:"+cause);
        }
    }
}
